package cn.tedu.property_management_system.service.Impl;

import cn.tedu.property_management_system.entity.DTO.UserDTO;
import cn.tedu.property_management_system.entity.VO.UserVO;
import cn.tedu.property_management_system.ex.ServiceException;
import cn.tedu.property_management_system.mapper.UserMapper;
import cn.tedu.property_management_system.service.IUserService;
import cn.tedu.property_management_system.utils.Constant;
import cn.tedu.property_management_system.utils.JsonResult;
import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.Header;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;

import static cn.tedu.property_management_system.utils.Constant.SECRET_KEY;
import static cn.tedu.property_management_system.utils.JsonResult.State.BAD_REQUEST;

@Service
@Slf4j
public class UserServiceImpl implements IUserService {

    @Autowired
    AuthenticationManager authenticationManager;

    @Autowired
    UserMapper userMapper;

    @Override
    public String login(UserDTO userDTO) {
        log.debug("准备认证");
        if (userDTO == null) {
            log.debug("传入用户参数为空");
            throw new ServiceException(BAD_REQUEST, "传入参数有误");
        }
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
                userDTO.getUsername(), userDTO.getPassword()
        );
        //用户名密码验证
        Authentication authenticate = authenticationManager.authenticate(token);
        //角色验证
        UserVO byUsername = userMapper.findByUsername(userDTO.getUsername());
        log.debug("输入的权限信息为[{}]");
        if (!byUsername.getRoleIds().contains(userDTO.getRoleId())){
            throw new ServiceException(BAD_REQUEST, "输入权限信息不正确,请联系管理员");
        }
        //取出authenticate中用户信息封装进map,为claims做准备
        User principal = (User) authenticate.getPrincipal();
        HashMap<String, Object> claims = new HashMap<>();
        claims.put("username", principal.getUsername());
        claims.put("password", principal.getPassword());
        log.debug("封装权限[{}]进入JWT",principal.getAuthorities());
        claims.put("permissions", JSON.toJSONString(principal.getAuthorities()));
        //封装JWT
        String jwt = Jwts.builder()
                .setHeaderParam(Header.TYPE, Header.JWT_TYPE)
                .setHeaderParam(Header.CONTENT_TYPE, "HS256")
                .setClaims(claims)
                .setExpiration(new Date(System.currentTimeMillis() + 5 * 60 * 30 * 1000))
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY)
                .compact();
        log.debug("封装jwt数据为[{}]",jwt);
        return jwt;
    }


}
